import 'package:fluent_ui/fluent_ui.dart';

import './config.dart';
import './model/setting_model.dart';
import './utils/local_storage.dart';

///全局配置
class GlobalSetting {
  GlobalSetting._();

  static final GlobalSetting _singleton = GlobalSetting._();

  factory GlobalSetting() => _singleton;

  static const _key = "gobal-settings";
  final _model = SettingModel(baseUrl: apiBaseUrl);

  ///是否已登录
  bool get isAuth => _model.isAuth;

  ///获取接口地址
  String get baseUrl => _model.baseUrl;

  ///获取租户ID
  String get tenant => _model.tenant;

  ///获取访问令牌
  String get accessToken => _model.accessToken;

  ///获取刷新令牌
  String get refreshToken => _model.refreshToken;

  ///获取昵称
  String get nick => _model.nick;

  ///获取头像地址
  String get avatar => _model.avatar;

  ///加载本地存储值
  Future<SettingModel?> loadLocal() =>
      localStorage.getValByKey(_key).then((data) {
        if (data != null) {
          final model = SettingModel.fromMap(data);
          _model.copy(model);
          return _model;
        }
        return null;
      });

  ///保存数据
  Future<bool> saveLocal(final SettingModel model) async {
    var ret = true;
    model.baseUrl = apiBaseUrl;
    final isChange = _model.copy(model);
    if (isChange) {
      debugPrint("保存本地变量 $_key=> ${model.toMap()}");
      ret = await localStorage.save(_key, model.toMap());
    }
    return ret;
  }

  ///清空令牌
  Future<bool> cleanToken() => saveLocal(SettingModel(
        baseUrl: apiBaseUrl,
        accessToken: "",
        refreshToken: "",
        nick: "",
        avatar: "",
      ));
}

///全局配置单例
final globalSetting = GlobalSetting();
